import Vue from 'vue'
import VueRouter from 'vue-router'
// 引入组件
// 引入store
import store from '@/store/index'
const Layout = () => import('@/views/layout/index.vue')
const Login = () => import('@/views/login/index.vue')
const Edit = () => import('@/views/layout/User/edit.vue')
const Search = () => import('@/views/search/index.vue')
const SearchResult = () => import('@/views/search/result.vue')
const Article = () => import('@/views/article/index.vue')
const Chat = () => import('@/views/layout/User/chat.vue')
// 404页面
const NotFound = () => import('@/views/404/NotFound.vue')
// 引入二级路由 默认找index.vue所以可以省略
const Home = () => import('@/views/layout/Home')
const QA = () => import('@/views/layout/QA')
const Video = () => import('@/views/layout/Video')
const User = () => import('@/views/layout/User')

// 如果路由重复跳转到同一个地址会报错
// 解决路由报错问题
// https://github.com/vuejs/vue-router/issues/2881#issuecomment-520554378
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    // 二级路由  不写/会自动拼接一级路由的地址
    children: [
      {
        path: '',
        component: Home,
        // 等于true在路由出口处经过判断就会被缓存
        meta: { isKeepAlive: true }
      },
      {
        path: 'qa',
        component: QA
      },
      {
        path: 'video',
        component: Video
      },
      {
        path: 'user',
        component: User
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  // 修改用户信息
  {
    path: '/user/edit',
    component: Edit
  },
  // 搜索模块
  {
    path: '/search',
    component: Search
  },
  // 搜索结果模块
  {
    path: '/search/result',
    component: SearchResult
  },
  // 详情页
  {
    path: '/article/:id',
    component: Article
  },
  // 小智同学
  {
    path: '/user/chat',
    component: Chat
  },
  // 没有满足条件的就访问这个404页面
  {
    path: '*',
    // 重定向到/404，网页上地址显示404
    redirect: '/404'
  },
  {
    path: '/404',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})

// 路由守卫 类似于请求拦截器
router.beforeEach((to, from, next) => {
  // 1.如果有token，直接放行
  // 2.如果没有token，判断去的页面需不需要token，需要token就返回到登录页，不需要token直接放行
  // 创建白名单用来保存需要token的页面
  const loginUrls = ['/user', '/user/edit']
  const token = store.state.user.token.token
  // console.log(to, from)
  // 有token
  if (token) {
    return next()
  }
  // 没有token,判断跳过去的页面需不需要token，如果需要也跳转到登录页
  if (loginUrls.includes(to.path)) {
    // 跳转的时候把去的页面存在地址栏里，便于回跳--->如果访问一个页面被拦截到了login页面，登录成功后继续跳转去之前要去的页面
    router.push({
      path: '/login',
      query: {
        back: to.path
      }
    })
  } else {
    next()
  }
})

export default router
